//
//  ShopDetailTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/9/3.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HXPhotoPicker

class ShopDetailTableViewController: BaseTableViewController {
    
    @IBOutlet weak var storeName: UITextField!
    @IBOutlet weak var principal: UITextField!
    @IBOutlet weak var address: UILabel!
    @IBOutlet weak var addressDetail: UITextView!
    @IBOutlet weak var phone: UITextField!
    @IBOutlet weak var storeImage: UIImageView! // 门店照片
    @IBOutlet weak var businessLicenseImage: UIImageView! // 营业执照
    
    
    
    var businessLicenseImgUrl = ""
    
    lazy var manager:HXPhotoManager = {
        var mager = HXPhotoManager.init(type: HXPhotoManagerSelectedType.photo)
        var configuration = HXPhotoConfiguration.init()
        configuration.movableCropBox = true
        configuration.movableCropBoxEditSize = true
        configuration.singleSelected = true
        configuration.requestImageAfterFinishingSelection = true
        mager?.configuration = configuration
        return mager!
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = Utils.getUserDefaulsFor(key: "storeName") as? String
        self.addressDetail.isUserInteractionEnabled = false
        self.storeImage.contentMode = .scaleAspectFill
        self.storeName.text = Utils.getUserDefaulsFor(key: "storeName") as? String
        self.principal.text = Utils.getUserDefaulsFor(key: "name") as? String
        self.phone.text = Utils.getUserDefaulsFor(key: "phone") as? String
        self.address.text = (Utils.getUserDefaulsFor(key: "provinceName") as! String) + (Utils.getUserDefaulsFor(key: "cityName") as! String) + (Utils.getUserDefaulsFor(key: "areaName") as! String)
        self.addressDetail.text = Utils.getUserDefaulsFor(key: "address") as! String
        self.storeImage.my_setImage(url: Utils.getUserDefaulsFor(key: "storeImg") as! String, placeholder: Api.placeHolder.rawValue)
        if Utils.getUserDefaulsFor(key: "licenseImg") as! String != "" {
            self.businessLicenseImage.my_setImage(url: UserDefaults.standard.object(forKey: "licenseImg") as! String, placeholder: Api.header.rawValue)
            self.businessLicenseImage.contentMode = .scaleAspectFill
        }
        else{
            let imageTap = UITapGestureRecognizer.init(target: self, action: #selector(imageViewTap(tap:)))
            self.businessLicenseImage.isUserInteractionEnabled = true
            self.businessLicenseImage.addGestureRecognizer(imageTap)
        }
        
        self.principal.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.phone.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
    }
    
    @objc func valueChange(textField:UITextField){
        var maxLength = 0
        if textField == self.principal {
            maxLength = 10
        }else{
            maxLength = 11
        }
        
        let toBeString = textField.text!
        let lang = textField.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = textField.markedTextRange
            if selectedRange == nil && toBeString.count > maxLength{
                let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
                textField.text = String(toBeString[..<endIndex])
            }
        }else if toBeString.count > maxLength {
            let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
            textField.text = String(toBeString[..<endIndex])
        }
    }
    
    @objc func imageViewTap(tap:UITapGestureRecognizer){
        self.hx_presentAlbumListViewController(with: self.manager, done: { (allList, photoList, videoList, imgArray, original, ctrl) in
            self.navigationController?.navigationBar.isTranslucent = false
            self.businessLicenseImage.contentMode = .scaleAspectFill
            self.businessLicenseImage.image = imgArray!.first
            self.uploadImage(img: imgArray!.first!)
        }) { (ctrl) in
            self.navigationController?.navigationBar.isTranslucent = false
        }
        
    }
    
    func uploadImage(img:UIImage){
        PKhud.showProgress(title: "处理中~")
        HttpRequest.uploadImage(image: img) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                self.businessLicenseImgUrl = result["data"] as! String
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func changeUserInfo(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.userUpdate.rawValue, parameters: ["name":self.principal.text!,"phone":self.phone.text!,"licenseImg":self.businessLicenseImgUrl]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: "修改成功~")
                UserDefaults.standard.set(self.principal.text!, forKey: "name")
                UserDefaults.standard.set(self.phone.text!, forKey:"phone" )
                if self.businessLicenseImgUrl != "" {
                    UserDefaults.standard.set(self.businessLicenseImgUrl, forKey: "licenseImg")
                }
                UserDefaults.standard.synchronize()
                Utils.DispatchAfter(after: 3, handler: {
                    self.backBarButtonMethon()
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:提交资料
    @IBAction func submitUserInfo(_ sender: UIButton) {
        self.changeUserInfo()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return section == 0 ? 5 : 1
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.width, height: 43))
        header.backgroundColor = UIColor.backgroundColor
        var title = ""
        if section == 0 {
            title = "门店信息"
        }else if section == 1 {
            title = "门店照片"
        }else {
            if Utils.getUserDefaulsFor(key: "licenseImg") as! String != "" {
                title = "营业执照上传"
            }else{
                title = "营业执照上传（请完善）"
            }
        }
        let label = Utils.labelWith(frame: CGRect.init(x: 12, y: 0, width: UIScreen.ScreenWidth - 12, height: 43), font: UIFont.boldSystemFont(ofSize: 13), textAlignment: .left, textColor: "#000000", text: title)
        header.addSubview(label)
        return header
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 43
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

}
